{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.functional as F\n",
    "import torch.optim as optim\n",
    "from torchvision import datasets,transforms\n",
    "\n",
    "epochs = 10\n",
    "batch_size = 200\n",
    "learning_rate = 0.001\n",
    "\n",
    "\n",
    "train_loader = torch.utils.data.DataLoader(\n",
    "    datasets.MNIST('../data',train=True,\n",
    "                    transform=transforms.Compose([transforms.ToTensor(),\n",
    "                    transforms.Normalize((0.1307,),(0.3081,))])),\n",
    "    batch_size = batch_size,shuffle = True)\n",
    "test_loader = torch.utils.data.DataLoader(\n",
    "    datasets.MNIST('../data',train=False,\n",
    "                    transform=transforms.Compose([transforms.ToTensor(),\n",
    "                    transforms.Normalize((0.1307,),(0.3081,))])),\n",
    "    batch_size = batch_size,shuffle = True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class MLP(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(MLP,self).__init__()\n",
    "        self.model = nn.Sequential(\n",
    "            nn.Linear(784,200),\n",
    "            nn.ReLU(inplace = True),\n",
    "            nn.Linear(200,200),\n",
    "            nn.ReLU(inplace = True),\n",
    "            nn.Linear(200,10),\n",
    "            nn.ReLU(inplace=True)\n",
    "        )\n",
    "    \n",
    "    def forward(self,x):\n",
    "        x = self.model(x)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train epoch: 0 [0/60000 (0%)] \t Loss: 6.593610\n",
      "Train epoch: 0 [20000/60000 (33%)] \t Loss: 1.319084\n",
      "Train epoch: 0 [40000/60000 (67%)] \t Loss: 1.043107\n"
     ]
    }
   ],
   "source": [
    "model = MLP()\n",
    "#L2 正则化\n",
    "#optimizer = optim.Adam(model.parameters(),lr=learning_rate,weight_decay = 0.001)\n",
    "optimizer = optim.Adam(model.parameters(),lr=learning_rate)\n",
    "criterion = nn.CrossEntropyLoss()\n",
    "\n",
    "for epoch in range(epochs):\n",
    "    for idx,(train,target) in enumerate(train_loader):\n",
    "        train = train.view(-1,28*28)#torch.Size([200, 1, 28, 28])\n",
    "        logits = model(train)#torch.Size([200, 10])\n",
    "#         loss = criterion(logits,target)\n",
    "        #print(loss.type())torch.FloatTensor\n",
    "        \n",
    "        #L1正则\n",
    "        regular_loss = 0.0\n",
    "        for para in model.parameters():\n",
    "            regular_loss += torch.sum(torch.abs(para))\n",
    "        r_loss = criterion(logits,target)\n",
    "        loss = r_loss + 0.001 * regular_loss\n",
    "        \n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "    \n",
    "        if idx%100 == 0:\n",
    "            print('Train epoch: {} [{}/{} ({:.0f}%)] \\t Loss: {:.6f}'\n",
    "                      .format(epoch,idx*len(train),len(train_loader.dataset),100. * idx / len(train_loader),loss.item()))\n",
    "    test_loss = 0\n",
    "    correct = 0\n",
    "    for data,tar in test_loader:\n",
    "        data = data.view(-1,28*28)#\n",
    "        logs = model(data)\n",
    "        test_loss += criterion(logs,tar).item()\n",
    "        pre_data = logs.data.max(1)[1]#torch.Size([200, 10])\n",
    "        #print(logs.data.max(1)[0])\n",
    "        #print(logs.data.max(1)[1])\n",
    "        correct += pre_data.eq(tar).sum()\n",
    "    test_loss /= len(test_loader.dataset)\n",
    "    print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n",
    "        test_loss, correct, len(test_loader.dataset),\n",
    "        100. * correct / len(test_loader.dataset)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
